export default {
    data: () => ({
        pagination: {
            page: 1,
            size: 10,
            total: 0,
            layout: "total, sizes, prev, pager, next, jumper",
        },
        list: [],
        searchObject: {},
        autoFetchList: true,
        selection: [],
    }),
    methods: {
        handlePageChange(page) {
            this.pagination.page = page
            this.fetchList()
        },
        handleSizeChange(size) {
            this.pagination.size = size
            this.fetchList()
        },
        resetPage() {
            this.pagination.page = 1
            this.fetchList()
        },
        fetchList() {
            this.$store.dispatch(this.fetchListAction, {
                ...this.searchObject,
                page: this.pagination.page,
                size: this.pagination.size,
            }).then(data => {
                this.pagination.total = data.total
                this.list = data.list

                typeof this.afterFetchList === "function" && this.afterFetchList(data)
            }).catch(() => {
                this.list = []
                this.pagination.total = 0
            })
        },

        handleSelectionChange(val) {
            this.selection = val
            console.log(val);
        },

        getFilterSelection(field = []) {
            if (!Array.isArray(field)) {
                field = [field]
            }
            return this.selection.map(el => {
                const res = {}
                field.forEach(key => res[key] = el[key])
                const keys = Object.keys(res)
                if (keys.length <= 1) {
                    return res[keys[0]]
                }
                return res
            })
        },
    },
    created() {
        if (this.autoFetchList) {
            this.fetchList()
        }
    },
}
